package com.example.servlet;


import com.alibaba.fastjson.JSON;
import com.example.domain.Users;
import com.example.dao.UserDao;
import com.example.dao.imp.UserDaoImp;
import com.example.utils.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;

@WebServlet(name = "RegisterServlet", value = "/registerServlet")
public class RegisterServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 读取请求体中的 JSON 数据
        BufferedReader reader = request.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        reader.close();
        // 解析 JSON 数据并转换为 Users 对象
        Users newUser = JSON.parseObject(jsonBuilder.toString(), Users.class);

        newUser.setCreatedAt(new Date());
        // 处理接收到的用户对象
        UserDao userDao = new UserDaoImp();
         userDao.addUser(newUser);

        ResponseUtil.sendSuccessResponse(response, 200, "注册成功");
    }
}
